package com.example.controller;

import com.example.annotations.Controller;
import com.example.annotations.RequestMapping;
import com.sun.net.httpserver.HttpExchange;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping(value = "/")
public class HomeController {

    @RequestMapping(value = "/getUser")
    public String getUser(HttpExchange httpExchange,String name){

        return name;
    }

    @RequestMapping(value = "/updateUser")
    public String updateUser(HttpExchange httpExchange,String name){

        return name;
    }

    @RequestMapping(value = "/deleteUser")
    public String deleteUser(HttpExchange httpExchange,String name){

        return name;
    }

    @RequestMapping(value = "/findUser")
    public String findUser(HttpExchange httpExchange,String name){

        return name;
    }

    @RequestMapping(value = "/test")
    public void test(HttpExchange httpExchange){
        String result = "hello test";
        byte[] totalByte = result.toString().getBytes(StandardCharsets.UTF_8);
        try {
            httpExchange.getResponseHeaders().add("content-type","text/html;charset=utf-8");
            httpExchange.sendResponseHeaders(200,totalByte.length);
            OutputStream os = httpExchange.getResponseBody();
            InputStream is = new ByteArrayInputStream(totalByte);
            byte[] buf = new byte[1024];
            int len = -1;
            while((len=is.read(buf))>-1){
                os.write(buf,0,len);
                os.flush();
            }
            os.close();
            is.close();
            System.out.println("离开test");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
